import ReactDom from 'react-dom/client'
import { notification } from 'antd'
import { useEffect } from 'react'
import { BasicToastProps } from './index.type'

export default function InitMessageCtx() {
  return <div id="i-toast"></div>
}

function BaseToast({ show, type, title = '提示', description }: BasicToastProps) {
  const [doNotification, notificationCtx] = notification.useNotification()

  useEffect(() => {
    if (show) {
      showNotification()
    }
  }, [show])

  function showNotification() {
    console.log(2222222, doNotification[type])
    doNotification[type]?.({
      message: title,
      description: description
    })
  }

  return notificationCtx
}

export class BasicToastFactory {
  private show(props: Omit<BasicToastProps, 'show'>) {
    const root = this.createToast()
    root.render(<BaseToast {...props} show={true} />)

    setTimeout(() => {
      root.unmount()
    }, props.duration || 1800)
  }

  success(msg: string) {
    this.show({
      title: '提示',
      description: msg,
      type: 'success'
    })
  }

  error(msg: string) {
    this.show({
      title: '错误',
      description: msg,
      type: 'error'
    })
  }

  warning(title: string, description?: string) {
    this.show({
      title,
      description,
      type: 'warning'
    })
  }

  public createToast() {
    return ReactDom.createRoot(document.getElementById('i-toast')!)
  }
}

export const toast = new BasicToastFactory()
